package com.eda;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.EditText;
import android.widget.Spinner;

import com.eda.common.ValueConvert;
import com.eda.db.DatabaseHelper;

public class PubPublishActivity extends Activity {

	EditText mobile;
	EditText start;
	EditText end;
	EditText cargoName;
	EditText type;
	EditText length;
	EditText startDate;
	DatabaseHelper mOpenHelper;
	Spinner spprovince;
	Spinner spcity;
	Spinner sparea;
	SQLiteDatabase db;
	EditText tempLocation;
	final static int TYPE = 1;
	final static int LOCATION = 2;
	final static int DATEPICKER = 3;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_pub_publish_tab);
		
		mOpenHelper = new DatabaseHelper(this);
		db = mOpenHelper.getWritableDatabase();
		mobile = (EditText)findViewById(R.id.pubPubMobile);
		cargoName = (EditText)findViewById(R.id.pubPubCargos);
		length = (EditText)findViewById(R.id.pubPubLengthRequire);
		startDate = (EditText)findViewById(R.id.pubPubStartDate);
		
		start = (EditText)findViewById(R.id.pubPubStart);
		start.setFocusable(false);
		start.setClickable(true);
		start.setInputType(InputType.TYPE_NULL);
		start.setOnClickListener(locationListener);
		
		end = (EditText)findViewById(R.id.pubPubEnd);
		end.setFocusable(false);
		end.setClickable(true);
		end.setInputType(InputType.TYPE_NULL);
		end.setOnClickListener(locationListener);
		
		type = (EditText)findViewById(R.id.pubPubTypeRequire);
		type.setFocusable(false);
		type.setClickable(true);
		type.setInputType(InputType.TYPE_NULL);
		type.setOnClickListener(locationListener);
		
		Button datePicker = (Button)findViewById(R.id.pubPubDatePicker);
		datePicker.setOnClickListener(datePickerListener);
		
		Button publish = (Button)findViewById(R.id.pubPubPublish);
		publish.setOnClickListener(publishListener);
		
		Button reset = (Button)findViewById(R.id.pubPubReset);
		reset.setOnClickListener(resetListener);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.pub_publish_tab, menu);
		return true;
	}
	
	//时间选择事件
	OnClickListener datePickerListener = new OnClickListener() {
		
		@Override
		public void onClick(View arg0) {
			showDialog(DATEPICKER);
			
		}
	};
	
	//输入框点击事件
	OnClickListener locationListener = new OnClickListener() {
		
		@Override
		public void onClick(View arg0) {
			tempLocation = (EditText)arg0;
			if(arg0.getId()==R.id.pubPubTypeRequire){
				showDialog(TYPE);
			}else{
				showDialog(LOCATION);
			}
		}
	};
	
	@Override
	protected Dialog onCreateDialog(int id) {
		switch(id){
		case LOCATION:
			return buildProviceDialog(PubPublishActivity.this);
		case TYPE:
			return buildTypeDialog(PubPublishActivity.this);
		case DATEPICKER:
			return buildDateDialog(PubPublishActivity.this);
		default:
			return null;
			
		
		}
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		setTitle("start");
	}

	//地区选择弹出框
	private Dialog buildProviceDialog(Context context) {
				
		LayoutInflater inflater = LayoutInflater.from(this);
		final View provinceView = inflater.inflate(R.layout.location_layout, null);
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setView(provinceView);
		builder.setTitle(R.string.alert_dialog_text_entry);
		
		spprovince = (Spinner)provinceView.findViewById(R.id.spprovince);
		spcity = (Spinner)provinceView.findViewById(R.id.spcity);
		sparea = (Spinner)provinceView.findViewById(R.id.sparea);
		
		String[] col = {"cityName"};
		Cursor cur =  db.query("province", col, "parentid=0", null, null, null, null);
		
		List<String> provinceList = new ArrayList<String>();
		while(cur.moveToNext()){
			provinceList.add(cur.getString(0));
		}
		ArrayAdapter provinceAdapter = new ArrayAdapter(PubPublishActivity.this, android.R.layout.simple_spinner_item, provinceList);
		provinceAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // 样式
	    spprovince.setAdapter(provinceAdapter);
	    spprovince.setOnItemSelectedListener(provinceSelectedListener);
		
	    builder.setPositiveButton(R.string.alert_dialog_ok,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
							
						}
					}
				);
		
		builder.setNegativeButton(R.string.alert_dialog_cancel,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						tempLocation.setText("");
					}
				});
	    
		return builder.create();
	}
	
	
	//选择省事件
	 private OnItemSelectedListener provinceSelectedListener = new OnItemSelectedListener() {
	        @Override
	        public void onItemSelected(AdapterView<?> parent, View view,
	                int position, long id) {
	            try {
	                Spinner spProvince = (Spinner) parent;
	                String selectedProvince = (String) spProvince.getItemAtPosition(position);
	                ArrayAdapter cityAdapter = null;
	                
	    			String[] col = {"codeid","cityName"};
	    			Cursor cur =  db.query("province", col, "cityName='"+selectedProvince+"'", null, null, null, null);
	    			int pid =-1;
	    			if(cur.moveToNext()){
	    				pid = cur.getInt(0);// 得到省份的id
	    			}
	    			
	    			cur = db.query("province", col, "parentid="+pid, null, null, null, null);
	    			
	                List<String> cityList = new ArrayList<String>();
	                while(cur.moveToNext()){
	                	cityList.add(cur.getString(1));
	    			}
	                cityAdapter = new ArrayAdapter(PubPublishActivity.this,
	                        android.R.layout.simple_spinner_item, cityList);
	                cityAdapter
	                        .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	                spcity.setAdapter(cityAdapter);
	                spcity.setOnItemSelectedListener(citySelectedListener);
	            } catch (Exception e) {
	                Log.d("WineStock", "Select Province error:" + e.getMessage());
	            }
	        }
	        
	        @Override
	        public void onNothingSelected(AdapterView<?> parent) {
	            // TODO Auto-generated method stub
	        }
	 };   
	 
	 //选择市事件
	 private OnItemSelectedListener citySelectedListener = new OnItemSelectedListener() {
	        @Override
	        public void onItemSelected(AdapterView<?> parent, View view,
	                int position, long id) {
	            try {
	                Spinner spCity = (Spinner) parent;
	                String selectedCity = (String) spCity.getItemAtPosition(position);
	                ArrayAdapter areaAdapter = null;
	                
	    			String[] col = {"codeid","cityName"};
	    			Cursor cur =  db.query("province", col, "cityName='"+selectedCity+"'", null, null, null, null);
	    			int pid =-1;
	    			if(cur.moveToNext()){
	    				pid = cur.getInt(0);// 得到省份的id
	    			}
	    			
	    			cur = db.query("province", col, "parentid="+pid, null, null, null, null);
	    			
	                List<String> areaList = new ArrayList<String>();
	                while(cur.moveToNext()){
	                	areaList.add(cur.getString(1));
	    			}
	                areaAdapter = new ArrayAdapter(PubPublishActivity.this,
	                        android.R.layout.simple_spinner_item, areaList);
	                areaAdapter
	                        .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	                sparea.setAdapter(areaAdapter);
	                sparea.setOnItemSelectedListener(areaSelectedListener);
	            } catch (Exception e) {
	                Log.d("WineStock", "Select Province error:" + e.getMessage());
	            }
	        }
	        
	        private OnItemSelectedListener citySelectedListener = new OnItemSelectedListener() {
		        @Override
		        public void onItemSelected(AdapterView<?> parent, View view,
		                int position, long id) {
		            try {
		                Spinner spCity = (Spinner) parent;
		                String selectedCity = (String) spCity.getItemAtPosition(position);
		                ArrayAdapter areaAdapter = null;
		                
		    			String[] col = {"codeid","cityName"};
		    			Cursor cur =  db.query("province", col, "cityName='selectedProvince'", null, null, null, null);
		    			int pid =-1;
		    			if(cur.moveToNext()){
		    				pid = cur.getInt(0);// 得到省份的id
		    			}
		    			
		    			cur = db.query("province", col, "parentid="+pid, null, null, null, null);
		    			
		                List<String> areaList = new ArrayList<String>();
		                if(cur.moveToNext()){
		                	areaList.add(cur.getString(1));
		    			}
		                areaAdapter = new ArrayAdapter(PubPublishActivity.this,
		                        android.R.layout.simple_spinner_item, areaList);
		                areaAdapter
		                        .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		                sparea.setAdapter(areaAdapter);
		                sparea.setOnItemSelectedListener(areaSelectedListener);
		            } catch (Exception e) {
		                Log.d("WineStock", "Select Province error:" + e.getMessage());
		            }
		        }
		        
		        @Override
		        public void onNothingSelected(AdapterView<?> parent) {
		            // TODO Auto-generated method stub
		        }
		 };
	        @Override
	        public void onNothingSelected(AdapterView<?> parent) {
	            // TODO Auto-generated method stub
	        }
	 };
	 
	 //选择区事件
	 private OnItemSelectedListener areaSelectedListener = new OnItemSelectedListener() {
	        @Override
	        public void onItemSelected(AdapterView<?> parent, View view,
	                int position, long id) {
	        	
	                Spinner spArea = (Spinner) parent;
	                String selectedCity = (String) spArea.getItemAtPosition(position);
	                tempLocation.setText(selectedCity);
	        }
	        
	        @Override
	        public void onNothingSelected(AdapterView<?> parent) {
	            // TODO Auto-generated method stub
	        }
	 };
	 
	 //车型选择弹出框
	 private Dialog buildTypeDialog(Context context) {
			
			LayoutInflater inflater = LayoutInflater.from(this);
			final View provinceView = inflater.inflate(R.layout.location_layout, null);
			AlertDialog.Builder builder = new AlertDialog.Builder(context);
			builder.setView(provinceView);
			builder.setTitle(R.string.alert_dialog_text_entry);
			
			spprovince = (Spinner)provinceView.findViewById(R.id.spprovince);
			
			String[] col = {"name"};
			db = mOpenHelper.getWritableDatabase();
			Cursor cur =  db.query("truck", col, null, null, null, null, null);
			
			List<String> provinceList = new ArrayList<String>();
			while(cur.moveToNext()){
				provinceList.add(cur.getString(0));
			}
			ArrayAdapter provinceAdapter = new ArrayAdapter(PubPublishActivity.this, android.R.layout.simple_spinner_item, provinceList);
			provinceAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // 样式
		    spprovince.setAdapter(provinceAdapter);
		    spprovince.setOnItemSelectedListener(typeSelectedListener);
			
		    builder.setPositiveButton(R.string.alert_dialog_ok,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
								
							}
						}
					);
			
			builder.setNegativeButton(R.string.alert_dialog_cancel,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							tempLocation.setText("");
						}
					});
		    
			return builder.create();
		}
	 
	 //车型选择事件
	 private OnItemSelectedListener typeSelectedListener = new OnItemSelectedListener() {
	        @Override
	        public void onItemSelected(AdapterView<?> parent, View view,
	                int position, long id) {
	        	
	                Spinner spType = (Spinner) parent;
	                String type = (String) spType.getItemAtPosition(position);
	                tempLocation.setText(type);
	        }
	        
	        @Override
	        public void onNothingSelected(AdapterView<?> parent) {
	            // TODO Auto-generated method stub
	        }
	 };
	 
	//日期选择弹出框
	 private Dialog buildDateDialog(Context context) {
			
			LayoutInflater inflater = LayoutInflater.from(this);
			final View datePickerView = inflater.inflate(R.layout.activity_date_pick, null);
			AlertDialog.Builder builder = new AlertDialog.Builder(context);
			builder.setView(datePickerView);
			builder.setTitle(R.string.alert_dialog_text_entry);
			
			DatePicker dp = (DatePicker)datePickerView.findViewById(R.id.date_picker);
			dp.init(2000, 1, 1, dateChangeListener);
			
		    builder.setPositiveButton(R.string.alert_dialog_ok,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
								
							}
						}
					);
			
			builder.setNegativeButton(R.string.alert_dialog_cancel,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							startDate.setText("");
						}
					});
		    
			return builder.create();
		}
	 
	 OnDateChangedListener dateChangeListener = new OnDateChangedListener() {
		
		@Override
		public void onDateChanged(DatePicker arg0, int arg1, int arg2, int arg3) {
			startDate = (EditText)findViewById(R.id.pubPubStartDate);
			startDate.setText(arg1+"年"+(arg2+1)+"月"+arg3+"日");
			
		}
	};
	
	//发布货源
	OnClickListener publishListener = new OnClickListener() {
		
		@Override
		public void onClick(View arg0) {
			SharedPreferences loginInfo = getSharedPreferences("LOGGING_INFO",0);
			String name = loginInfo.getString("USER_NAME", "");

			String url = ValueConvert.URL+"/pubCargo.do?userId="+name+
					"&mobile="+mobile.getText().toString()+
					"&start="+start.getText().toString()+
					"&end="+end.getText().toString()+
					"&cargoName="+cargoName.getText().toString()+
					"&type="+type.getText().toString()+
					"&length="+length.getText().toString()+
					"&startDate="+startDate.getText().toString();
			
			HttpClient client = new DefaultHttpClient();
			HttpPost request;
			try {
				request = new HttpPost(new URI(url));
				
				HttpParams params=client.getParams(); //计算网络超时用. 
				HttpConnectionParams.setConnectionTimeout(params, 3000);
				HttpConnectionParams.setSoTimeout(params, 5000);
				
				HttpResponse response = client.execute(request);
				// 判断请求是否成功
				if (response.getStatusLine().getStatusCode() == 200) {
					HttpEntity entity = response.getEntity();
					if (entity != null) {
						String out = EntityUtils.toString(entity);
						if(out!=null){
							
							if(ValueConvert.convert(out).get(0).get(0).equals("success")){
								new AlertDialog.Builder(PubPublishActivity.this).setMessage("发布成功").create().show();
							}else{
								new AlertDialog.Builder(PubPublishActivity.this).setMessage("发布失败").create().show();
							}
						}
					}
				}
			} catch (Exception e) {
				new AlertDialog.Builder(PubPublishActivity.this).setMessage("发布失败").create().show();
			} 
		}
	};
	
	//点击重置
	OnClickListener resetListener = new OnClickListener() {
		
		@Override
		public void onClick(View arg0) {
			mobile.setText("");
			start.setText("");
			end.setText("");
			cargoName.setText("");
			type.setText("");
			length.setText("");
			startDate.setText("");
		}
	};
}
